package person.wend.pluginm;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class LoadUtil {

    public LoadUtil(String pluginName) {
        this.pluginName = pluginName;
        this.pluginPath = getPluginPath(pluginName);
    }

    /**
     * jarLoader的缓冲
     */
    private static Map<String, JarLoader> jarLoaderCenter = new HashMap();
    /**
     * 插件名称
     */
    private String pluginName;
    /**
     * 插件路径
     */
    private String pluginPath;

    public static String getPluginPath(String pluginName) {

        String DEFAULT_PLUGIN_PATH = System.getProperty("user.dir") + File.separator + pluginName + File.separator + "target" + File.separator;
        // 读plugin.json 文件
        File pluginFile = new File(DEFAULT_PLUGIN_PATH);
        if (!pluginFile.exists()) {
            throw new IllegalArgumentException("插件不存在.");
        }
        return pluginFile.getAbsolutePath();
    }

    public String getClassName() {
        // pluginName Class首字母大写
        String pluginNameClass = pluginName.substring(0, 1).toUpperCase() + pluginName.substring(1);

        return "person.wend." + pluginName + ".provider" + "." + pluginNameClass + "Provider";
    }

    public synchronized JarLoader getJarLoader() {

        JarLoader jarLoader = jarLoaderCenter.get(pluginName);
        if (null == jarLoader) {
            if (StringUtils.isBlank(pluginPath)) {
                throw new IllegalArgumentException("插件路径非法.");
            }
            jarLoader = new JarLoader(new String[]{pluginPath});
            jarLoaderCenter.put(pluginName, jarLoader);
        }

        return jarLoader;
    }
}
